#!/usr/bin/env python
import inspect
import os
import sys
import importlib

import manimlib.constants as consts
from manimlib.constants import PRODUCTION_QUALITY_CAMERA_CONFIG
from manimlib.config import get_module
from manimlib.extract_scene import is_child_scene

"""
At the moment, I think it's broken, 
and I wouldn't worry about it too much. 
It's something which is meant to organize all the scenes generated 
from a given file in your file system so that as you move them to a video editor 
they automatically go in in the correct order.

Arguably it shouldn't be in this repo, 
but it's not too far off from being more generally useful 
if I were to go in and clean it up a bit.

现在，我认为它坏了，我不会太担心它。
它是指在你的文件系统中组织所有由给定文件生成的场景，
这样当你将它们移动到视频编辑器时，它们会自动按正确的顺序进入。[编好视频的顺序进入视频编辑软件里]

可以说，它不应该出现在这个回购中，但如果我进去把它清理一下，它就离更普遍的用途不远了。



Changed the way Scene write to videos, 
where it writes each play or wait call as a separate file, 
and later concatenates them together. 
The main motivation here is to make it so that stage_scenes can stack together more granular movie files, 
which makes video editing a little more seamless, 
since effectively all the cuts are already at the right points.

There is an added benefit that while long scenes are rendering, 
one can actually see the partial progress as it gets rendered.

改变了场景写入视频的方式，将每个播放或等待调用作为一个单独的文件写入，
然后将它们连接在一起。这里的主要动机是使stage_scenes可以将更多的颗粒状电影文件堆叠在一起，
这使得视频编辑更加无缝，因为实际上所有的剪切都已经在正确的点上了。

还有一个好处是，当长场景渲染的时候，你可以看到部分的进展。
"""


def get_sorted_scene_classes(module_name):
    module = get_module(module_name)
    if hasattr(module, "SCENES_IN_ORDER"):
        return module.SCENES_IN_ORDER
    # Otherwise, deduce from the order in which
    # they're defined in a file
    importlib.import_module(module.__name__)
    line_to_scene = {}
    name_scene_list = inspect.getmembers(
        module,
        lambda obj: is_child_scene(obj, module)
    )
    for name, scene_class in name_scene_list:
        if inspect.getmodule(scene_class).__name__ != module.__name__:
            continue
        lines, line_no = inspect.getsourcelines(scene_class)
        line_to_scene[line_no] = scene_class
    return [
        line_to_scene[index]
        for index in sorted(line_to_scene.keys())
    ]


def stage_scenes(module_name):
    scene_classes = get_sorted_scene_classes(module_name)
    if len(scene_classes) == 0:
        print("There are no rendered animations from this module")
        return
    # output_directory_kwargs = {
    #     "camera_config": PRODUCTION_QUALITY_CAMERA_CONFIG,
    # }
    # TODO, fix this
    animation_dir = os.path.join(
        os.path.expanduser('~'),
        "Dropbox (3Blue1Brown)/3Blue1Brown Team Folder/videos",
        "bayes", "1440p60"
    )
    animation_dir = '/Users/a1/PycharmProjects/manim/from_victor/videos'
    files = os.listdir(animation_dir)
    sorted_files = []
    for scene_class in scene_classes:
        scene_name = scene_class.__name__
        clips = [f for f in files if f.startswith(scene_name + ".")]
        for clip in clips:
            sorted_files.append(os.path.join(animation_dir, clip))
        # Partial movie file directory
        # movie_dir = get_movie_output_directory(
        #     scene_class, **output_directory_kwargs
        # )
        # if os.path.exists(movie_dir):
        #     for extension in [".mov", ".mp4"]:
        #         int_files = get_sorted_integer_files(
        #             pmf_dir, extension=extension
        #         )
        #         for file in int_files:
        #             sorted_files.append(os.path.join(pmf_dir, file))
        # else:

    # animation_subdir = os.path.dirname(animation_dir)
    count = 0
    while True:
        staged_scenes_dir = os.path.join(
            animation_dir,
            os.pardir,
            "staged_scenes_{}".format(count)
        )
        if not os.path.exists(staged_scenes_dir):
            os.makedirs(staged_scenes_dir)
            break
        # Otherwise, keep trying new names until
        # there is a free one
        count += 1
    for count, f in reversed(list(enumerate(sorted_files))):
        # Going in reversed order means that when finder
        # sorts by date modified, it shows up in the
        # correct order
        symlink_name = os.path.join(
            staged_scenes_dir,
            "Scene_{:03}_{}".format(
                count, f.split(os.sep)[-1]
            )
        )
        os.symlink(f, symlink_name)


if __name__ == "__main__":
    # if len(sys.argv) < 2:
    #     raise Exception("No module given.")
    # module_name = sys.argv[1]
    module_name = 'from_victor/all_test_scenes.py'
    stage_scenes(module_name)
